from django.contrib.auth.decorators import login_required
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import SAFE_METHODS
from rest_framework.response import Response
import decimal
from .models import Good
from .serializers import GoodAllowSerializer, GoodSuperSerializer
from django.http import HttpResponse, JsonResponse
from rest_framework import permissions
from .filterBackend import GoodPermissionFilterBackend
from rest_framework.pagination import PageNumberPagination

from utils.decorators.responses import json_response, FlagException
from utils.decorators.auth import is_superuser, is_authenticated
from django.contrib.auth import get_user_model
UserModel = get_user_model()


# 分页实现
class GoodsPagination(PageNumberPagination):
    page_size = 100
    page_query_param = "page"
    page_size_query_param = 'limit'

    # 最大能请求几条
    max_page_size = 100


class GoodViewSet(viewsets.mixins.CreateModelMixin,
                  viewsets.mixins.RetrieveModelMixin,
                  viewsets.mixins.UpdateModelMixin,
                  viewsets.mixins.ListModelMixin,
                  viewsets.GenericViewSet):
    pagination_class = GoodsPagination
    queryset = Good.objects.all()
    serializer_class = GoodSuperSerializer
    permission_classes = (
         permissions.IsAuthenticatedOrReadOnly,
    )
    filter_backends = [
        GoodPermissionFilterBackend,
    ]

    # def get_serializer_class(self):
    #     if self.request.user.is_superuser:
    #         return GoodSuperSerializer
    #     else:
    #         return GoodAllowSerializer

    @is_authenticated
    @json_response
    def list(self, request, *args, **kwargs):
        pass


    @is_authenticated
    @json_response
    def retrieve(self, request, *args, **kwargs):
        user = UserModel.objects.get(pk=kwargs['pk'])
        queryset = Good.objects.all()
        serializer = GoodSuperSerializer(queryset, many=True)
        data = serializer.data
        for i, v in enumerate(data):
            if decimal.Decimal(v["isDiscount"]) == 1:
                data[i]["discount"] = user.discount if user.discount else data[i]["discount"]
            else:
                data[i]["discount"] = 1
        return data


@login_required()
def getGood(request):
    print(request.user.is_superuser)
    return HttpResponse("OK")



